package me.wpf.utils;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

/**
 * Description: es连接池工厂
 *
 * @author 王朋飞
 * @create 2019/11/6
 */
public class EsClientPoolFactory implements PooledObjectFactory<RestHighLevelClient> {

    private HttpHost[] hosts;

    public EsClientPoolFactory(String hostName) {
        String[] split = hostName.split(",");
        this.hosts = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String[] host = split[i].split(":");
            HttpHost info = new HttpHost(host[0], Integer.parseInt(host[1]), "http");
            this.hosts[i] = info;
        }
    }

    @Override
    public PooledObject<RestHighLevelClient> makeObject() throws Exception {
        RestHighLevelClient client = null;
        try {
            client = new RestHighLevelClient(RestClient.builder(this.hosts));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new DefaultPooledObject<RestHighLevelClient>(client);

    }

    @Override
    public void destroyObject(PooledObject<RestHighLevelClient> pooledObject) throws Exception {
        RestHighLevelClient highLevelClient = pooledObject.getObject();
        highLevelClient.close();
    }

    @Override
    public boolean validateObject(PooledObject<RestHighLevelClient> pooledObject) {
        return true;
    }

    @Override
    public void activateObject(PooledObject<RestHighLevelClient> pooledObject) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<RestHighLevelClient> pooledObject) throws Exception {

    }
}
